package com.openx.xframework.spring.boot.autoconfigue.web;

import com.openx.xframework.common.exception.ParameterErrorException;
import com.openx.xframework.common.model.ErrorInfo;
import com.openx.xframework.common.model.ParameterError;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

@ControllerAdvice
@ResponseBody
public class GlobalExceptionHandler {

    private static final Logger logger = LoggerFactory.getLogger(GlobalExceptionHandler.class);

    /**
     * 参数错误.返回400
     */
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    @ExceptionHandler(ParameterErrorException.class)
    public ErrorInfo handleParameterException(HttpServletRequest request, ParameterErrorException exception) {
        List<ParameterError> errors  = ParameterError.valueOf(((ParameterErrorException) exception).getErrors());

        return ErrorInfo.ParameterError(getPath(request),errors,exception.getMessage());
    }




    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    @ExceptionHandler(Exception.class)
    public ErrorInfo handleException(HttpServletRequest request,Exception exception) {
        logger.debug("--调试信息--GlobalExceptionHandler is working! :)");
        return  ErrorInfo.serverError(getPath(request),HttpStatus.INTERNAL_SERVER_ERROR,exception.getMessage());
    }


    private String getPath(HttpServletRequest request){
        return request.getRequestURL().toString();
    }
}